/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 本系统已申请软件著作权，受国家版权局知识产权以及国家计算机软件著作权保护！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2020 陈尼克 all rights reserved.
 * 版权所有，侵权必究！
 */
import axios from "axios";
import { showToast, showFailToast, showConfirmDialog } from "vant";
import { getToken, setToken } from "@/utils/auth.js";
import { useStore } from "@/stores/user";
import router from "../router";

// axios.defaults.baseURL = import.meta.env.MODE == "development" ? "//backend-api-01.newbee.ltd/api/v1" : "//backend-api-01.newbee.ltd/api/v1";
axios.defaults.baseURL = import.meta.env.VITE_BASE_API;
axios.defaults.withCredentials = false;
axios.defaults.timeout = import.meta.env.VITE_TIMEOUT;
axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers["token"] = getToken() || "";
axios.defaults.headers["Content-Type"] = "application/json;charset=UTF-8;";

axios.interceptors.request.use(
  (config) => {
    config.headers["token"] = getToken();
    return config;
  },
  (error) => {
    if (error.code === "ECONNABORTED" && error.message.indexOf("timeout") !== -1) {
      showFailToast("请求超时！");
    }
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (res) => {
    const code = res.data.code || 0;
    if (code != 0) {
      if (res.data.msg) showFailToast(res.data.msg);
      if (res.data.msg && res.data.msg.indexOf("过期") > -1) {
        showConfirmDialog({
          title: "提示！",
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          message: "登录状态已过期，您可以继续留在该页面，或者重新登录。",
        })
          .then(() => {
            const store = useStore();
            store.resetToken().then(() => {
              router.push({ path: "/login" }).catch(() => {});
            });
          })
          .catch(() => {});
      }
      return Promise.reject(res.data);
    }
    return res.data;
  },
  (error) => {
    showFailToast("请求错误！");
    return Promise.reject(error);
  }
);

export default axios;

//其他接口地址，会继承axios的默认配置，包括拦截器，
//如果不需要token可以为这个实例再配个拦截器，以覆盖全局拦截器
export const axiosHw = axios.create({
  baseURL: "",
  timeout: "30000",
  headers: {
    "Content-Type": "application/json;charset=UTF-8;",
    token: "",
  },
});
